// ignore_for_file: non_constant_identifier_names

part of base_package;

class Net {
  static String logText = '';
  static bool isShowLogBtn = false;

  ///默认地址
  static String DEFAULT_IP = '';

  /// 是否显示log日志
  static String IS_SHOW_LOG_BTN = 'IS_SHOW_LOG_BTN';

  static int EVENT_NetLogPage = -100;

  static Dio dio = Dio();
  static Dio tempDio = Dio();

  /// 初始化网络请求数据
  /// baseUrl 服务器接口地址
  /// headers 请求头参数
  static init(String baseUrl, Map<String, dynamic> headers) {
    dio.options.baseUrl = baseUrl;
    dio.options.headers = headers;
    dio.interceptors.clear();
    dio.interceptors.add(NetLog());
    dio.interceptors.add(
        DioCacheInterceptor(options: CacheOptions(store: MemCacheStore())));
    DEFAULT_IP = baseUrl;
  }

  /// get请求
  /// intf 接口名称
  /// param 请求参数
  /// headers 请求头参数
  /// success 成功的回调
  /// error 失败的回调
  static get(String intf,
      {Map<String, dynamic>? param,
      Map<String, dynamic>? headers,
      Function? success,
      Function? error}) async {
    _request(intf, param, headers, false, "GET", success, error);
  }

  /// post请求
  /// intf 接口名称
  /// param 请求参数
  /// headers 请求头参数
  /// success 成功的回调
  /// error 失败的回调
  static post(String intf,
      {Map<String, dynamic>? param,
      Map<String, dynamic>? headers,
      Function? success,
      bool isBigData = false,
      Function? error}) async {
    _request(intf, param, headers, isBigData, "POST", success, error);
  }

  static _request(
      String intf,
      Map<String, dynamic>? param,
      Map<String, dynamic>? headers,
      bool isBigData,
      String method,
      Function? success,
      Function? error) async {
    try {
      /// 解决https无法访问的问题
      // (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
      //     (client) {
      //   // 证书不校验，放行
      //   client.badCertificateCallback =
      //       (X509Certificate cert, String host, int port) {
      //     return true;
      //   };
      // };
      var respone = method == "GET"
          ? await dio.get(intf,
              queryParameters: param,
              options: Options(headers: headers, method: method))
          : await dio.post(intf,
              queryParameters: isBigData ? {} : param,
              data: param,
              options: Options(headers: headers, method: method));
      success!(respone.data);
    } catch (e) {
      error!(e);
      catchHandle(e);
    }
  }

  static upImgBase64(String intf,
      {Map<String, dynamic>? param,
      Map<String, dynamic>? headers,
      Function? success,
      Function? error}) async {
    try {
      /// 解决https无法访问的问题
      // (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
      //     (client) {
      //   // 证书不校验，放行
      //   client.badCertificateCallback =
      //       (X509Certificate cert, String host, int port) {
      //     return true;
      //   };
      // };
      var respone = await dio.post(intf,
          data: param, options: Options(headers: headers, method: 'POST'));
      success!(respone.data);
    } catch (e) {
      error!(e);
      catchHandle(e);
    }
  }

  /// download 下载
  /// urlPath 下载地址
  /// savePath 保存地址
  /// param 请求参数
  /// headers 请求头参数
  /// progress 进度回调
  /// finish 完成回调
  /// error 失败回调
  static download(String urlPath, String savePath,
      {Map<String, dynamic>? param,
      Map<String, dynamic>? headers,
      Function? progress,
      Function? finish,
      Function? error}) async {
    try {
      /// 解决https无法访问的问题
      // (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
      //     (client) {
      //   // 证书不校验，放行
      //   client.badCertificateCallback =
      //       (X509Certificate cert, String host, int port) {
      //     return true;
      //   };
      // };
      await dio.download(urlPath, savePath,
          onReceiveProgress: (int count, int total) {
        progress!((count / total * 100).toStringAsFixed(0) + "%");
        if (count == total) {
          finish!(savePath);
        }
      }, queryParameters: param, options: Options(headers: headers));
    } catch (e) {
      error!(e);
      catchHandle(e);
    }
  }

  /// 文件上传
  static putFile(String intf, File file,
      {Map<String, dynamic>? param, Function? success, Function? error}) async {
    try {
      /// 解决https无法访问的问题
      // (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
      //     (client) {
      //   // 证书不校验，放行
      //   client.badCertificateCallback =
      //       (X509Certificate cert, String host, int port) {
      //     return true;
      //   };
      // };
      FormData formdata = FormData.fromMap({
        "file": await MultipartFile.fromFile(
          file.path, //图片路径
          filename: FileUtil.getFileName(file.path),
        ), //文件名称
      });
      // param["file"] = await MultipartFile.fromFile(
      //   file.path, //图片路径
      //   filename: Util.getFileName(file.path),
      // ); //图片
      var respone = await dio.post(
        intf,
        data: formdata,
        queryParameters: param,
      );
      success!(respone.data);
    } catch (e) {
      error!(e);
      catchHandle(e);
    }
  }

  /// downloadTemp 临时dio下载
  /// urlPath 下载地址
  /// savePath 保存地址
  /// param 请求参数
  /// headers 请求头参数
  /// progress 进度回调
  /// finish 完成回调
  /// error 失败回调
  static downloadTemp(String urlPath, String savePath,
      {Map<String, dynamic>? param,
      Map<String, dynamic>? headers,
      Function? progress,
      Function? finish,
      Function? error}) async {
    try {
      await tempDio.download(urlPath, savePath,
          onReceiveProgress: (int count, int total) {
        progress!((count / total * 100).toStringAsFixed(0) + "%");
        if (count == total) {
          finish!(savePath);
        }
      }, queryParameters: param, options: Options(headers: headers));
    } catch (e) {
      error!(e);
      catchHandle(e);
    }
  }

  static catchHandle(var e) {
    if (e.response == null) {
      if (e.error.message.isEmpty || e.error.osError.errorCode == 101) {
        EasyLoading.showToast("网络异常，请检查网络");
        return;
      }
    } else {
      if (e.response.statusCode == 404) {
        EasyLoading.showToast("服务器连接异常");
        return;
      }
      if (e.response.statusCode == 500) {
        EasyLoading.showToast("服务器异常");
        return;
      }
      if (e.response.statusCode == 401 || e.response.statusCode == 400) {
        EasyLoading.showToast(e.response.data['msg'].toString());
        return;
      }
    }
  }
}
